package com.we.risk.phoneRecord.var.dimphone;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.we.risk.phoneRecord.common.PhoneRecordDataUtils;
import org.apache.commons.io.FileUtils;
import org.apache.flink.util.Collector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.we.risk.phoneRecord.var.dimphone.TagCallRecord.getNameTags;

public class DimPhoneRecordLabelCompare {
    public static final String RELEASEPROP =
            "risk/phonerecord/stage2/dim_phone_kfk_self_test.properties";
    public static final String PROPSETS = "risk/phonerecord/phonerecord.properties";
    public static Logger LOG = LoggerFactory.getLogger(DimPhoneRecordLabelCompare.class);

    public static final String MOBILE_AREA_BROADCAST_DESC = "phonerecord_mob_area_broad_cast_desc";
    public static final int MOBILE_AREA_BROADCAST_WAIT_SEC = 15 * 1000;
    public static final String SPLITWORD = "#";
    public static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String MSGTYPE = "HFQ_UPLOAD_PHONE_CALL_RECORD";
    public static final String INPUTKEYBY = "userKey";
    public static final String OUTPUTKEY = "user_key";
    public static final String TIMESTAMP = "timestamp";
    public static final String HTTPTIMESTAMP = "httpTimestamp";
    public static final String JOBID = "jobID";
    public static final String PHONECALLLIST = "phoneCallList";
    public static final String REMOVEJSONKEY = "numberType";
    public static final Long KFKMSGMAXSIZE = 20 * 1024 * 1024L;
    public static final HashMap<String, Integer> mobileOptMap = new HashMap<>();
    public static final HashMap<String, Integer> callTypeMap = new HashMap<>();

    public static void main(String[] args) throws IOException {
        try {

            File input =
                    new File(
                            "/Users/jk/Downloads/风控标签需求/实时需求/通话记录-loulingbo/Stage3/cmp/22641ccfa8ef076b35925a5125e65225.json");
            File sgTag =
                    new File(
                            "/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/risk_phone_record_sougou_cuishou_tag_all_jkuse.txt");

            File mobAreaIspData =
                    new File(
                            "/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/phone_format_porv_city_isp");
            File csTagV2 = new File("/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/callrecord_cstag_v2_data");
            File outfile =
                    new File(
                            "/Users/jk/Downloads/风控实时标签需求/通话记录-loulingbo/data_compare/1106/phone_compare.data");

            HashMap<String, String> sgMap = initSgCsTagMap(sgTag);
            HashMap<String, String> mobAreaIspMap = initMobAreaIspMap(mobAreaIspData);
            HashMap<String, String> csTagV2Map = initCsTagV2Map(csTagV2);

            initMobileOptMap();
            initCallTypeMap();

            String inputStr = FileUtils.readFileToString(input);
            JSONObject inputJson = JSONObject.parseObject(inputStr);

            if (inputJson != null && inputJson.getString("type").equals(MSGTYPE)) {
                JSONObject dataJson = inputJson.getJSONObject("dataJson");
                JSONObject job = dataJson.getJSONObject("job");
                String jobID = job.getString(JOBID);

                String userKey = dataJson.getString(INPUTKEYBY);
                JSONObject data = dataJson.getJSONObject("data");
                JSONObject baseData = data.getJSONObject("baseData");
                Long recv_time = null;
                if(baseData != null) {
                    recv_time = baseData.getLong(HTTPTIMESTAMP);
                }
                JSONArray calls = data.getJSONArray(PHONECALLLIST);
                JSONObject outJson = new JSONObject();

                if (userKey != null) {
                    outJson.put(OUTPUTKEY, userKey);
                    outJson.put(HTTPTIMESTAMP, recv_time);
                    outJson.put(JOBID, jobID);
                    outJson.put(PHONECALLLIST, calls);

                    formatCallList(outJson, sgMap, csTagV2Map, mobAreaIspMap);
//                    ProcessData(outJson, sgMap, mobAreaIspMap, csTagV2Map);
//                    ProcessData(outJson, sgMap, v1CleanMap, mobAreaIspMap, csTagV2Map);
                }
                FileUtils.writeStringToFile(outfile, outJson.toString());
            }

        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            LOG.error("Exception: " + e.toString());
            e.printStackTrace();
        }
    }

    private static void initMobileOptMap() {
        mobileOptMap.put("中国联通", 1);
        mobileOptMap.put("中国移动", 2);
        mobileOptMap.put("中国电信", 3);
    }

    private static void initCallTypeMap() {
//            callTypeMap.put("UNKNOWN", 0);
        callTypeMap.put("INCOMING", 1);
        callTypeMap.put("MISSED", 2);
        callTypeMap.put("OUTGOING", 3);
        callTypeMap.put("REJECTED", 4);
        callTypeMap.put("BLOCKED", 5);
    }


    private static HashMap<String, String> initSgCsTagMap(File sgTagFile) throws IOException {
        HashMap<String, String> sgMap = new HashMap<>();
        List<String> sgTagLines = FileUtils.readLines(sgTagFile);
        for (String line : sgTagLines) {
            String[] splits = line.split(",");
            if (splits.length == 3) {
                String phone_num = splits[0];
                String sgTag = splits[1];
                String coName = splits[2];
                String mapKey = phone_num;
                String mapVal = sgTag + SPLITWORD + coName;
                sgMap.put(mapKey, mapVal);
            } else {
                LOG.error("DimPhoneRecordLabel initSgCsTagMap error read line: " + line);
            }
        }
        return sgMap;
    }

    private static HashMap<String, String> initMobAreaIspMap(File mobArea) throws Exception {
        {
            HashMap<String, String> mobAreaIspMap = new HashMap<>();
            List<String> sgTagLines = FileUtils.readLines(mobArea);
            for (String line : sgTagLines) {
                String[] splits = line.split(",");
                if (splits.length == 4) {
                    String mobile = splits[0];
                    String province = splits[1];
                    String city = splits[2];
                    String isp = splits[3];
                    if (province == null || province.equals("")) {
                        province = "null";
                    }

                    if (city == null || city.equals("")) {
                        city = "null";
                    }
                    if (isp == null || isp.equals("")) {
                        isp = "null";
                    }

                    mobAreaIspMap.put(mobile, province + SPLITWORD + city + SPLITWORD + isp);
                } else {
                    System.out.println(
                            "DimPhoneRecordLabel initMobAreaMap error read line: " + line);
                }
            }
            return mobAreaIspMap;
        }
    }

    private static HashMap<String, String> initCsTagV2Map(File csTagV2) throws Exception {
        HashMap<String, String> csTagV2Map = new HashMap<>();

        List<String> sgTagLines = FileUtils.readLines(csTagV2);
        for (String line : sgTagLines) {
            csTagV2Map.put(line,"");
        }
        return csTagV2Map;
    }

    private static String[] MapMobAreaIsp(String mobile, HashMap<String, String> mobileAreaMap) throws Exception {
        String res = mobileAreaMap.get(mobile);
        try {
            if(res != null) {
                String[] splits = res.split(SPLITWORD);
                if (splits.length == 3) {
                   return splits;
                }
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("MapMobAreaIsp exception input mobile: " + mobile);
        }
        return null;
    }

    /** 返回映射完全的地址+ISP运营商 */
    private static String[] MapMobAreaIsp(String mobile, HashMap<String, String> readBState, HashMap<String, String> v1CleanMap)
            throws Exception {

        String res = readBState.get(mobile);
        String[] outs = new String[3];
        try {
            if (res != null) {
                LOG.debug("MapMobArea get res: " + res);
                String[] splits = res.split(SPLITWORD);
                if (splits.length == 3) {
                    String mob_prov = (splits[0].equals("null") ? "" : splits[0]);
                    String mob_city = (splits[1].equals("null") ? "" : splits[1]);
                    String mob_isp = (splits[2].equals("null") ? "" : splits[2]);

                    String trans_key = mob_prov + SPLITWORD + mob_city;
                    String trans_val = v1CleanMap.get(trans_key);
                    LOG.debug("MapMobArea get trans_val: " + trans_val);
                    if (trans_val != null) {
                        String[] splitRes = trans_val.split(SPLITWORD);
                        if (splitRes.length == 2) {
                            LOG.debug(
                                    "MapMobArea get prov: "
                                            + splitRes[0]
                                            + " city: "
                                            + splitRes[1]);
                            outs[0] = splitRes[0];
                            outs[1] = splitRes[1];
                        } else {
                            LOG.warn(
                                    "DimPhoneRecordLabel MapMobArea V1Clean data error: "
                                            + trans_val);
                        }
                    } else {
                        LOG.warn("DimPhoneRecordLabel MapMobArea err trans_key: " + trans_key);
                    }
                    outs[2] = mob_isp;
                    return outs;

                } else {
                    LOG.warn("MobileAreaProcessFunc MapMobArea error res: " + res);
                }
            } else {
                LOG.debug("MapMobArea readBstate cant find mob : " + mobile);
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("MapMobAreaIsp exception input mobile: " + mobile);
        }
        return null;
    }

    private static void formatCallList(JSONObject inputJson,
                                HashMap<String, String> sgcsTagMap,
                                HashMap<String, String> csTagV2Map,
                                HashMap<String, String> mobAreaIspMap) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
//            JSONObject inputJson = JSONObject.parseObject(value);
            JSONArray phoneCallList = inputJson.getJSONArray(PHONECALLLIST);
            int callSize = phoneCallList.size();
            for (int i = 0; i < callSize; i++) {
                JSONObject callJson = (JSONObject) phoneCallList.get(i);
                if (callJson.containsKey(REMOVEJSONKEY)) {
                    callJson.remove(REMOVEJSONKEY);
                }

                Integer call_type = callTypeMap.get(callJson.getString("type"));
                callJson.put("call_type",(call_type == null ? 0 : call_type));
                if (callJson.containsKey("type")) {
                    callJson.remove("type");
                }

                Long call_time = callJson.getLong("date");
                callJson.put("call_time", sdf.format(new Date(call_time)));
                if(callJson.containsKey("date")) {
                    callJson.remove("date");
                }

                String name = callJson.getString("name");
                String number = callJson.getString("number");

                String nameTags = getNameTags(name, number);
                callJson.put("name_tags", nameTags);

                String phone = PhoneRecordDataUtils.getVarFormatedPhone(number);
                String mobile = PhoneRecordDataUtils.getVarMobile(phone);
                String phone_tags = PhoneRecordDataUtils.getVarPhoneTags(number);
                String f_phone = PhoneRecordDataUtils.forMattedPhoneNumber(number);

                callJson.put("phone", phone);
                callJson.put("mobile", mobile);
                callJson.put("phone_tags", phone_tags);
                callJson.put("f_phone", f_phone);

                if (callJson.containsKey("number")) {
                    callJson.remove("number");
                }

                if (f_phone != null) {
                    consSgCsTag(f_phone, sgcsTagMap, csTagV2Map, callJson);
                    if (f_phone.length() == 11) {
                        String subNumber = f_phone.substring(0, 7);
                        consMobAreaIsp(subNumber, mobAreaIspMap, callJson);
                    }
                }

                phoneCallList.set(i, callJson);
            }


        } catch (Exception e) {
            LOG.error("ProcessData exception: " + e.toString());
            LOG.error("ProcessData exception input: " + inputJson);
            e.printStackTrace();
        }
    }


    private static void consSgCsTag(String mobile,
                                    HashMap<String, String> sgcsMap,
                                    HashMap<String, String> csTagV2Map,
                                    JSONObject outJson) {
        try {
            String sgcsTag = sgcsMap.get(mobile);
            if (sgcsTag != null) {
                String[] splits = sgcsTag.split(SPLITWORD);
                if (splits.length == 2) {
                    outJson.put("phone_sgtag", splits[0]);
                    outJson.put("phone_cstag", splits[1]);
                }
            }
            outJson.put("phone_cstag_v2", (csTagV2Map.containsKey(mobile) ? 1 : 0));
        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("consSgCsTag exception input mobile: " + mobile);
        }
    }

    /** 返回映射完全的地址+ISP运营商 */
    private static void consMobAreaIsp(String mobile, HashMap<String, String> areaMap, JSONObject outJson) {
        try {
            String res = areaMap.get(mobile);
            if (res != null) {
                LOG.debug("MapMobArea get res: " + res);
                String[] splits = res.split(SPLITWORD);
                if (splits.length == 3) {
                    outJson.put("mobile_prov", splits[0]);
                    outJson.put("mobile_city", splits[1]);
                    Integer isp_code = mobileOptMap.get(splits[2]);
                    outJson.put("mobile_opt", (isp_code == null ? 0 : isp_code));
                }
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("MapMobAreaIsp exception input mobile: " + mobile);
        }
    }

}
